﻿<%@ WebHandler Language="C#" Class="APSPlanDashBoardV2" %>

using System;
using System.Web;
using Newtonsoft.Json;
using Newtonsoft.Json.Linq;
using Newtonsoft.Json.Converters;
using System.Collections.Generic;
using System.Data;
using System.Text;
using ReportBusiness;
using System.Collections;
using System.IO;

/**
 * Description: APS排产看板
 * Copyright (c): 通力凯顿（北京）系统集成有限公司
 * Author: zhunan
 * Date: 2023.4.19
 */

public class APSPlanDashBoardV2 : IHttpHandler
{
    uMESReportOracleDAL dal = new uMESReportOracleDAL();
    public bool IsReusable { get { return false; } }
    public void ProcessRequest(HttpContext context)
    {
        string requestjson = "";
        using (StreamReader reader = new StreamReader(context.Request.InputStream)) { requestjson = reader.ReadToEnd(); }
        JObject jObject = JsonConvert.DeserializeObject(requestjson) as JObject;
        if (jObject["type"] != null)
        {
            try
            {
                Result r = new Result();
                context.Response.ContentType = "text/json";
                string type = jObject["type"].ToString();
                switch (type)
                {
                    case "getData":
                        r = getData(jObject);//查询
                        context.Response.Write(JsonConvert.SerializeObject(r));
                        break;
                    case "exportExcel":
                        exportExcel(jObject);//导出
                        break;
                    case "exportExcel2":
                        exportExcel2(jObject);//导出
                        break;
                    default:
                        break;
                }
            }
            catch (Exception e)
            {
                Result r = new Result();
                r.data = null;
                r.meta = new Result.Meta(500, e.Message);
                r.total = 0;
                context.Response.ContentType = "text/json";
                context.Response.Write(JsonConvert.SerializeObject(r));
            }
        }
    }

    Result getData(JObject jObject)
    {
        string factoryid = "", workcenterid = "", teamid = "";
        JArray selectOrg = JArray.Parse(jObject["selectOrg"].ToString());
        if (selectOrg.Count == 3)
        {
            factoryid = selectOrg[0].ToString();
            workcenterid = selectOrg[1].ToString();
            teamid = selectOrg[2].ToString();
        }
        else if (selectOrg.Count == 2)
        {
            factoryid = selectOrg[0].ToString();
            workcenterid = selectOrg[1].ToString();
        }
        else if (selectOrg.Count == 1)
        {
            factoryid = selectOrg[0].ToString();
        }

        string sql = @"
SELECT rd.resourceid,rd.resourcename,rd.description,e.employeeid,e.fullname,e.employeename,rd.resourceid || e.employeeid id
FROM apsplandetail a
INNER JOIN apsplandetailemp ad ON ad.apsplandetailid = a.apsplandetailid AND ad.isuse = 0
INNER JOIN containercurrentinfo cci ON cci.containerid = a.containerid
LEFT JOIN employee e ON e.employeeid = ad.employeeid
INNER JOIN resourcedef rd ON rd.resourceid = a.resourceid";

        if (jObject["status"] != null && jObject["status"].ToString() != "")
        {
            sql += @"
LEFT JOIN (
    SELECT csd.*,row_number () OVER (PARTITION BY csd.containerid, csd.workflowstepid ORDER BY csd.checkdate) as rn
    FROM apsplandetail a
    INNER JOIN containersteprecord csd ON csd.containerid = a.containerid AND csd.workflowstepid = a.workflowstepid
    WHERE a.isuse = 0";
            if (jObject["selectdate"] != null && jObject["selectdate"].ToString() != "")
            {
                JArray arr = JArray.Parse(jObject["selectdate"].ToString());
                if (arr.Count >= 2)
                {
                    sql += string.Format(" AND a.endtime >= to_date('{0} 00:00:00','yyyy-MM-dd hh24:mi:ss')", arr[0].ToString());
                    sql += string.Format(" AND a.endtime <= to_date('{0} 23:59:59','yyyy-MM-dd hh24:mi:ss')", arr[1].ToString());
                }
            }
            sql += @"
) csd ON csd.containerid = a.containerid AND csd.workflowstepid = a.workflowstepid AND csd.rn = 1
";
        }

        sql += @"
WHERE a.isuse = 0 {0}
GROUP BY rd.resourceid,rd.resourcename,rd.description,e.employeeid,e.fullname,e.employeename";
        string query = "";
        //主制分厂
        if (factoryid != "")
        {
            query += string.Format(" AND cci.originalfactoryid = '{0}'", factoryid);
        }

        if (workcenterid != "")
        {
            query += string.Format(" AND a.workcenterid = '{0}'", workcenterid);
        }

        if (teamid != "")
        {
            query += string.Format(" AND a.teamid = '{0}'", teamid);
        }

        if (jObject["workerid"] != null && jObject["workerid"].ToString() != "")
        {
            query += string.Format(" AND ad.employeeid = '{0}'", jObject["workerid"].ToString());
        }

        if (jObject["resourcename"] != null && jObject["resourcename"].ToString() != "")
        {
            query += string.Format(" AND rd.resourcename = '{0}'", jObject["resourcename"].ToString());
        }

        if (jObject["mfgordername"] != null && jObject["mfgordername"].ToString() != "")
        {
            query += string.Format(" AND cci.mfgordername = '{0}'", jObject["mfgordername"].ToString());
        }

        if (jObject["productname"] != null && jObject["productname"].ToString() != "")
        {
            query += string.Format(" AND cci.productname = '{0}'", jObject["productname"].ToString());
        }

        if (jObject["containername"] != null && jObject["containername"].ToString() != "")
        {
            query += string.Format(" AND cci.containername = '{0}'", jObject["containername"].ToString());
        }

        if (jObject["selectdate"] != null && jObject["selectdate"].ToString() != "")
        {
            JArray arr = JArray.Parse(jObject["selectdate"].ToString());
            if (arr.Count >= 2)
            {
                query += string.Format(" AND a.endtime >= to_date('{0} 00:00:00','yyyy-MM-dd hh24:mi:ss')", arr[0].ToString());
                query += string.Format(" AND a.endtime <= to_date('{0} 23:59:59','yyyy-MM-dd hh24:mi:ss')", arr[1].ToString());
            }
        }

        if (jObject["status"] != null && jObject["status"].ToString() != "")
        {
            query += @" AND (CASE WHEN csd.usecompleted = 1 AND csd.checkdate <= a.endtime THEN '按时完成'
                    WHEN csd.usecompleted = 1 AND csd.checkdate > a.endtime THEN '超期完成'
                    WHEN NVL(csd.usecompleted,0) = 0 AND SYSDATE <= a.endtime THEN '未完成'
                    WHEN NVL(csd.usecompleted,0) = 0 AND SYSDATE > a.endtime THEN '超期未完'
               END)='" + jObject["status"].ToString() + "'";
        }

        sql = string.Format(sql, query);
        uMESPagingDataDTO dto = dal.GetPagingDataIns(sql, (int)jObject["currentPage"], (int)jObject["pageSize"]);
        DataTable dtResult = dto.DBTable;
        int columsCount = dtResult.Columns.Count;

        JArray colums = JArray.Parse(jObject["colums"].ToString());
        for (int i = 0; i < colums.Count; i++)
        {
            dtResult.Columns.Add(colums[i].ToString(), typeof(object));
        }

        sql = @"
SELECT a.apsplandetailid,cci.containerid,cci.workflowstepid,a.resourceid,f.factoryname,w.workcentername,t.teamname,e.fullname,ad.employeeid,
       rd.resourcename,rd.description,cci.mfgordername,mfg.qty mfgqty,mfg.plannedstartdate,
       cci.productname,cci.productdescription,cci.containerno,
       cci.containername,cci.qty,NULL specno,NULL opdesc,a.workflowstepname,
       a.starttime,TRUNC(a.endtime) endtime,csd.checkdate,
       CASE WHEN csd.usecompleted = 1 AND csd.checkdate <= a.endtime THEN '按时完成'
            WHEN csd.usecompleted = 1 AND csd.checkdate > a.endtime THEN '超期完成'
            WHEN NVL(csd.usecompleted,0) = 0 AND SYSDATE <= a.endtime THEN '未完成'
            WHEN NVL(csd.usecompleted,0) = 0 AND SYSDATE > a.endtime THEN '超期未完'
       END status,
       a.resourceid || ad.employeeid id
FROM apsplandetail a
LEFT JOIN apsplandetailemp ad ON ad.apsplandetailid = a.apsplandetailid AND a.isuse = 0
INNER JOIN containercurrentinfo cci ON cci.containerid = a.containerid
LEFT JOIN factory f ON f.factoryid = a.specfactoryid --排产分厂
LEFT JOIN workcenter w ON w.workcenterid = a.workcenterid --排产工区
LEFT JOIN team t ON t.teamid = a.teamid --排产班组
LEFT JOIN employee e ON e.employeeid = ad.employeeid
INNER JOIN resourcedef rd ON rd.resourceid = a.resourceid
LEFT JOIN mfgorder mfg ON mfg.mfgorderid = cci.mfgorderid
LEFT JOIN (
    SELECT csd.*,row_number () OVER (PARTITION BY csd.containerid, csd.workflowstepid ORDER BY csd.checkdate) as rn
    FROM apsplandetail a
    INNER JOIN containersteprecord csd ON csd.containerid = a.containerid AND csd.workflowstepid = a.workflowstepid
    WHERE a.isuse = 0";
        if (jObject["selectdate"] != null && jObject["selectdate"].ToString() != "")
        {
            JArray arr = JArray.Parse(jObject["selectdate"].ToString());
            if (arr.Count >= 2)
            {
                sql += string.Format(" AND a.endtime >= to_date('{0} 00:00:00','yyyy-MM-dd hh24:mi:ss')", arr[0].ToString());
                sql += string.Format(" AND a.endtime <= to_date('{0} 23:59:59','yyyy-MM-dd hh24:mi:ss')", arr[1].ToString());
            }
        }
        sql += @"
) csd ON csd.containerid = a.containerid AND csd.workflowstepid = a.workflowstepid AND csd.rn = 1
WHERE a.isuse = 0 {0}
ORDER BY a.starttime,cci.containername";
        sql = string.Format(sql, query);
        DataTable dt = dal.GetDataTable(sql);

        // 拆分出工序号、工序名称
        foreach (DataRow dr in dt.Rows)
        {
            string workflowstepname = dr["workflowstepname"].ToString();
            if (workflowstepname.Contains("-"))
            {
                string[] arr = workflowstepname.Split('-');
                dr["specno"] = arr[arr.Length - 2].ToString();
                dr["opdesc"] = arr[arr.Length - 1].ToString();
            }
        }

        foreach (DataRow dr in dtResult.Rows)
        {
            for (int i = columsCount; i < dtResult.Columns.Count; i++)
            {
                string filter = string.Format("id = '{0}' AND endtime='{1}'", dr["id"], dtResult.Columns[i].ColumnName);
                DataRow[] drList = dt.Select(filter);
                DataTable dtPlanSpec;
                if (drList.Length > 0)
                {
                    dtPlanSpec = drList.CopyToDataTable();
                    foreach (DataColumn col in dtPlanSpec.Columns)
                    {
                        col.ColumnName = col.ColumnName.ToLower();
                    }
                    dr[dtResult.Columns[i].ColumnName] = dtPlanSpec;
                }
                else
                {
                    dr[dtResult.Columns[i].ColumnName] = new DataTable();
                }
            }
        }

        foreach (DataColumn col in dtResult.Columns)
        {
            col.ColumnName = col.ColumnName.ToLower();
        }
        Result r = new Result();
        r.data = dtResult;
        r.total = Convert.ToInt32(dto.RowCount);
        r.meta = new Result.Meta(200, "请求成功");
        return r;
    }

    //导出
    void exportExcel(JObject jObject)
    {
        string sql = @"
SELECT f.factoryname,w.workcentername,t.teamname,rd.description,e.fullname,cci.mfgordername,cci.productname,cci.productdescription,
       cci.containername,cci.qty,a.workflowstepname,a.starttime,TRUNC(a.endtime) endtime,csd.checkdate,
       CASE WHEN csd.usecompleted = 1 AND csd.checkdate <= a.endtime THEN '按时完成'
            WHEN csd.usecompleted = 1 AND csd.checkdate > a.endtime THEN '超期完成'
            WHEN NVL(csd.usecompleted,0) = 0 AND SYSDATE <= a.endtime THEN '未完成'
            WHEN NVL(csd.usecompleted,0) = 0 AND SYSDATE > a.endtime THEN '超期未完'
       END status
FROM apsplandetail a
LEFT JOIN apsplandetailemp ad ON ad.apsplandetailid = a.apsplandetailid AND a.isuse = 0
INNER JOIN containercurrentinfo cci ON cci.containerid = a.containerid
LEFT JOIN factory f ON f.factoryid = a.specfactoryid --排产分厂
LEFT JOIN workcenter w ON w.workcenterid = a.workcenterid --排产工区
LEFT JOIN team t ON t.teamid = a.teamid --排产班组
INNER JOIN employee e ON e.employeeid = ad.employeeid
INNER JOIN resourcedef rd ON rd.resourceid = a.resourceid
LEFT JOIN (
    SELECT csd.*,row_number () OVER (PARTITION BY csd.containerid, csd.workflowstepid ORDER BY csd.checkdate) as rn
    FROM apsplandetail a
    INNER JOIN containersteprecord csd ON csd.containerid = a.containerid AND csd.workflowstepid = a.workflowstepid
    WHERE a.isuse = 0";
        if (jObject["selectdate"] != null && jObject["selectdate"].ToString() != "")
        {
            JArray arr = JArray.Parse(jObject["selectdate"].ToString());
            if (arr.Count >= 2)
            {
                sql += string.Format(" AND a.endtime >= to_date('{0} 00:00:00','yyyy-MM-dd hh24:mi:ss')", arr[0].ToString());
                sql += string.Format(" AND a.endtime <= to_date('{0} 23:59:59','yyyy-MM-dd hh24:mi:ss')", arr[1].ToString());
            }
        }
        sql += @"
) csd ON csd.containerid = a.containerid AND csd.workflowstepid = a.workflowstepid AND csd.rn = 1
WHERE a.isuse = 0 {0}
ORDER BY a.starttime,cci.containername";
        string factoryid = "", workcenterid = "", teamid = "";
        JArray selectOrg = JArray.Parse(jObject["selectOrg"].ToString());
        if (selectOrg.Count == 3)
        {
            factoryid = selectOrg[0].ToString();
            workcenterid = selectOrg[1].ToString();
            teamid = selectOrg[2].ToString();
        }
        else if (selectOrg.Count == 2)
        {
            factoryid = selectOrg[0].ToString();
            workcenterid = selectOrg[1].ToString();
        }
        else if (selectOrg.Count == 1)
        {
            factoryid = selectOrg[0].ToString();
        }

        string query = "";
        //主制分厂
        if (factoryid != "")
        {
            query += string.Format(" AND cci.originalfactoryid = '{0}'", factoryid);
        }

        if (workcenterid != "")
        {
            query += string.Format(" AND a.workcenterid = '{0}'", workcenterid);
        }

        if (teamid != "")
        {
            query += string.Format(" AND a.teamid = '{0}'", teamid);
        }

        if (jObject["workerid"] != null && jObject["workerid"].ToString() != "")
        {
            query += string.Format(" AND ad.employeeid = '{0}'", jObject["workerid"].ToString());
        }

        if (jObject["resourcename"] != null && jObject["resourcename"].ToString() != "")
        {
            query += string.Format(" AND rd.resourcename = '{0}'", jObject["resourcename"].ToString());
        }

        if (jObject["mfgordername"] != null && jObject["mfgordername"].ToString() != "")
        {
            query += string.Format(" AND cci.mfgordername = '{0}'", jObject["mfgordername"].ToString());
        }

        if (jObject["productname"] != null && jObject["productname"].ToString() != "")
        {
            query += string.Format(" AND cci.productname = '{0}'", jObject["productname"].ToString());
        }

        if (jObject["containername"] != null && jObject["containername"].ToString() != "")
        {
            query += string.Format(" AND cci.containername = '{0}'", jObject["containername"].ToString());
        }

        if (jObject["selectdate"] != null && jObject["selectdate"].ToString() != "")
        {
            JArray arr = JArray.Parse(jObject["selectdate"].ToString());
            if (arr.Count >= 2)
            {
                query += string.Format(" AND a.endtime >= to_date('{0} 00:00:00','yyyy-MM-dd hh24:mi:ss')", arr[0].ToString());
                query += string.Format(" AND a.endtime <= to_date('{0} 23:59:59','yyyy-MM-dd hh24:mi:ss')", arr[1].ToString());
            }
        }

        if (jObject["status"] != null && jObject["status"].ToString() != "")
        {
            query += @" AND (CASE WHEN csd.usecompleted = 1 AND csd.checkdate <= a.endtime THEN '按时完成'
                    WHEN csd.usecompleted = 1 AND csd.checkdate > a.endtime THEN '超期完成'
                    WHEN NVL(csd.usecompleted,0) = 0 AND SYSDATE <= a.endtime THEN '未完成'
                    WHEN NVL(csd.usecompleted,0) = 0 AND SYSDATE > a.endtime THEN '超期未完'
               END)='" + jObject["status"].ToString() + "'";
        }

        sql = string.Format(sql, query);

        DataTable dtResult = dal.GetDataTable(sql);

        foreach (DataColumn col in dtResult.Columns)
        {
            col.ColumnName = col.ColumnName.ToLower();
        }

        dtResult.Columns["factoryname"].Caption = "分厂";
        dtResult.Columns["workcentername"].Caption = "工区";
        dtResult.Columns["teamname"].Caption = "班组";
        dtResult.Columns["fullname"].Caption = "工人";
        dtResult.Columns["description"].Caption = "设备";
        dtResult.Columns["mfgordername"].Caption = "订单号";
        dtResult.Columns["productname"].Caption = "零件号";
        dtResult.Columns["productdescription"].Caption = "零件名称";
        dtResult.Columns["containername"].Caption = "批次号";
        dtResult.Columns["qty"].Caption = "数量";
        dtResult.Columns["workflowstepname"].Caption = "工序";
        dtResult.Columns["starttime"].Caption = "开始时间";
        dtResult.Columns["endtime"].Caption = "结束时间";
        dtResult.Columns["checkdate"].Caption = "时间完工时间";
        dtResult.Columns["status"].Caption = "状态";

        ExportHelper.ExportExcel(dtResult, "APS排产看板数据导出");
    }

    // 导出2
    void exportExcel2(JObject jObject)
    {
        string factoryid = "", workcenterid = "", teamid = "";
        JArray selectOrg = JArray.Parse(jObject["selectOrg"].ToString());
        if (selectOrg.Count == 3)
        {
            factoryid = selectOrg[0].ToString();
            workcenterid = selectOrg[1].ToString();
            teamid = selectOrg[2].ToString();
        }
        else if (selectOrg.Count == 2)
        {
            factoryid = selectOrg[0].ToString();
            workcenterid = selectOrg[1].ToString();
        }
        else if (selectOrg.Count == 1)
        {
            factoryid = selectOrg[0].ToString();
        }
        string sql = @"
SELECT rd.resourceid,rd.resourcename,rd.description,e.employeeid,e.fullname,e.employeename,rd.resourceid || e.employeeid ID
FROM apsplandetail a
INNER JOIN apsplandetailemp ad ON ad.apsplandetailid = a.apsplandetailid AND ad.isuse = 0
INNER JOIN containercurrentinfo cci ON cci.containerid = a.containerid
LEFT JOIN employee e ON e.employeeid = ad.employeeid
INNER JOIN resourcedef rd ON rd.resourceid = a.resourceid";

        if (jObject["status"] != null && jObject["status"].ToString() != "")
        {
            sql += @"
LEFT JOIN (
    SELECT csd.*,row_number () OVER (PARTITION BY csd.containerid, csd.workflowstepid ORDER BY csd.checkdate) as rn
    FROM apsplandetail a
    INNER JOIN containersteprecord csd ON csd.containerid = a.containerid AND csd.workflowstepid = a.workflowstepid
    WHERE a.isuse = 0";
            if (jObject["selectdate"] != null && jObject["selectdate"].ToString() != "")
            {
                JArray arr = JArray.Parse(jObject["selectdate"].ToString());
                if (arr.Count >= 2)
                {
                    sql += string.Format(" AND a.endtime >= to_date('{0} 00:00:00','yyyy-MM-dd hh24:mi:ss')", arr[0].ToString());
                    sql += string.Format(" AND a.endtime <= to_date('{0} 23:59:59','yyyy-MM-dd hh24:mi:ss')", arr[1].ToString());
                }
            }
            sql += @"
) csd ON csd.containerid = a.containerid AND csd.workflowstepid = a.workflowstepid AND csd.rn = 1
";
        }

        sql += @"
WHERE a.isuse = 0 {0}
GROUP BY rd.resourceid,rd.resourcename,rd.description,e.employeeid,e.fullname,e.employeename";
        string query = "";
        //主制分厂
        if (factoryid != "")
        {
            query += string.Format(" AND cci.originalfactoryid = '{0}'", factoryid);
        }

        if (workcenterid != "")
        {
            query += string.Format(" AND a.workcenterid = '{0}'", workcenterid);
        }

        if (teamid != "")
        {
            query += string.Format(" AND a.teamid = '{0}'", teamid);
        }

        if (jObject["workerid"] != null && jObject["workerid"].ToString() != "")
        {
            query += string.Format(" AND ad.employeeid = '{0}'", jObject["workerid"].ToString());
        }

        if (jObject["resourcename"] != null && jObject["resourcename"].ToString() != "")
        {
            query += string.Format(" AND rd.resourcename = '{0}'", jObject["resourcename"].ToString());
        }

        if (jObject["mfgordername"] != null && jObject["mfgordername"].ToString() != "")
        {
            query += string.Format(" AND cci.mfgordername = '{0}'", jObject["mfgordername"].ToString());
        }

        if (jObject["productname"] != null && jObject["productname"].ToString() != "")
        {
            query += string.Format(" AND cci.productname = '{0}'", jObject["productname"].ToString());
        }

        if (jObject["containername"] != null && jObject["containername"].ToString() != "")
        {
            query += string.Format(" AND cci.containername = '{0}'", jObject["containername"].ToString());
        }

        if (jObject["selectdate"] != null && jObject["selectdate"].ToString() != "")
        {
            JArray arr = JArray.Parse(jObject["selectdate"].ToString());
            if (arr.Count >= 2)
            {
                query += string.Format(" AND a.endtime >= to_date('{0} 00:00:00','yyyy-MM-dd hh24:mi:ss')", arr[0].ToString());
                query += string.Format(" AND a.endtime <= to_date('{0} 23:59:59','yyyy-MM-dd hh24:mi:ss')", arr[1].ToString());
            }
        }

        if (jObject["status"] != null && jObject["status"].ToString() != "")
        {
            query += @" AND (CASE WHEN csd.usecompleted = 1 AND csd.checkdate <= a.endtime THEN '按时完成'
                    WHEN csd.usecompleted = 1 AND csd.checkdate > a.endtime THEN '超期完成'
                    WHEN NVL(csd.usecompleted,0) = 0 AND SYSDATE <= a.endtime THEN '未完成'
                    WHEN NVL(csd.usecompleted,0) = 0 AND SYSDATE > a.endtime THEN '超期未完'
               END)='" + jObject["status"].ToString() + "'";
        }

        sql = string.Format(sql, query);
        DataTable dtResult = dal.GetDataTable(sql);
        int columsCount = dtResult.Columns.Count;

        JArray colums = JArray.Parse(jObject["colums"].ToString());
        for (int i = 0; i < colums.Count; i++)
        {
            dtResult.Columns.Add(colums[i]["value"].ToString(), typeof(object));
        }

        sql = @"
SELECT a.apsplandetailid,cci.containerid,cci.workflowstepid,a.resourceid,f.factoryname,w.workcentername,t.teamname,e.fullname,ad.employeeid,
       rd.resourcename,rd.description,cci.mfgordername,mfg.qty mfgqty,mfg.plannedstartdate,
       cci.productname,cci.productdescription,cci.containerno,
       cci.containername,cci.qty,NULL specno,NULL opdesc,a.workflowstepname,
       a.starttime,TRUNC(a.endtime) endtime,csd.checkdate,
       CASE WHEN csd.usecompleted = 1 AND csd.checkdate <= a.endtime THEN '按时完成'
            WHEN csd.usecompleted = 1 AND csd.checkdate > a.endtime THEN '超期完成'
            WHEN NVL(csd.usecompleted,0) = 0 AND SYSDATE <= a.endtime THEN '未完成'
            WHEN NVL(csd.usecompleted,0) = 0 AND SYSDATE > a.endtime THEN '超期未完'
       END status,
       a.resourceid || ad.employeeid id
FROM apsplandetail a
LEFT JOIN apsplandetailemp ad ON ad.apsplandetailid = a.apsplandetailid AND a.isuse = 0
INNER JOIN containercurrentinfo cci ON cci.containerid = a.containerid
LEFT JOIN factory f ON f.factoryid = a.specfactoryid --排产分厂
LEFT JOIN workcenter w ON w.workcenterid = a.workcenterid --排产工区
LEFT JOIN team t ON t.teamid = a.teamid --排产班组
LEFT JOIN employee e ON e.employeeid = ad.employeeid
INNER JOIN resourcedef rd ON rd.resourceid = a.resourceid
LEFT JOIN mfgorder mfg ON mfg.mfgorderid = cci.mfgorderid
LEFT JOIN (
    SELECT csd.*,row_number () OVER (PARTITION BY csd.containerid, csd.workflowstepid ORDER BY csd.checkdate) as rn
    FROM apsplandetail a
    INNER JOIN containersteprecord csd ON csd.containerid = a.containerid AND csd.workflowstepid = a.workflowstepid
    WHERE a.isuse = 0";
        if (jObject["selectdate"] != null && jObject["selectdate"].ToString() != "")
        {
            JArray arr = JArray.Parse(jObject["selectdate"].ToString());
            if (arr.Count >= 2)
            {
                sql += string.Format(" AND a.endtime >= to_date('{0} 00:00:00','yyyy-MM-dd hh24:mi:ss')", arr[0].ToString());
                sql += string.Format(" AND a.endtime <= to_date('{0} 23:59:59','yyyy-MM-dd hh24:mi:ss')", arr[1].ToString());
            }
        }
        sql += @"
) csd ON csd.containerid = a.containerid AND csd.workflowstepid = a.workflowstepid AND csd.rn = 1
WHERE a.isuse = 0 {0}
ORDER BY a.starttime,cci.containername";
        sql = string.Format(sql, query);
        DataTable dt = dal.GetDataTable(sql);

        // 拆分出工序号、工序名称
        foreach (DataRow dr in dt.Rows)
        {
            string workflowstepname = dr["workflowstepname"].ToString();
            if (workflowstepname.Contains("-"))
            {
                string[] arr = workflowstepname.Split('-');
                dr["specno"] = arr[arr.Length - 2].ToString();
                dr["opdesc"] = arr[arr.Length - 1].ToString();
            }
        }

        foreach (DataRow dr in dtResult.Rows)
        {
            for (int i = columsCount; i < dtResult.Columns.Count; i++)
            {
                string filter = string.Format("id = '{0}' AND endtime='{1}'", dr["id"], dtResult.Columns[i].ColumnName);
                DataRow[] drList = dt.Select(filter);
                DataTable dtPlanSpec;
                if (drList.Length > 0)
                {
                    dtPlanSpec = drList.CopyToDataTable();
                    foreach (DataColumn col in dtPlanSpec.Columns)
                    {
                        col.ColumnName = col.ColumnName.ToLower();
                    }
                    string value = "";
                    foreach (DataRow row in dtPlanSpec.Rows)
                    {
                        value += string.Format("{0}【{1}】\n", row["containername"].ToString(), row["specno"].ToString());
                    }
                    dr[dtResult.Columns[i].ColumnName] = value.TrimEnd('\n');
                }
                else
                {
                    dr[dtResult.Columns[i].ColumnName] = "";
                }
            }
        }

        foreach (DataColumn col in dtResult.Columns)
        {
            for (int i = 0; i < colums.Count; i++)
            {
                string value = colums[i]["value"].ToString();
                string label = colums[i]["label"].ToString();
                if (col.ColumnName.ToString() == value)
                {
                    col.Caption = label;
                    break;
                }
            }
            col.ColumnName = col.ColumnName.ToLower();
        }

        dtResult.Columns.Remove("resourceid");
        dtResult.Columns.Remove("employeeid");
        dtResult.Columns.Remove("employeename");
        dtResult.Columns.Remove("id");
        dtResult.Columns["description"].Caption = "设备名称";
        dtResult.Columns["resourcename"].Caption = "设备编号";
        dtResult.Columns["fullname"].Caption = "人员";
        ExportHelper.ExportExcel(dtResult, "APS排产看板数据导出");
    }
}